<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author dong
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'jydq:product:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <div ref="chartRef" class="h-70 w-full"></div>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsJydqProductForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { JydqProduct, jydqProductSave, jydqProductForm } from '/@/api/jydq/jydqProduct';
  import { categoryTreeData } from '/@/api/jydq/jydqCategory';

  import { EChartsOption } from 'echarts';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { Ref } from 'vue/dist/vue';
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('jydq.jydqProduct');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<JydqProduct>({} as JydqProduct);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增商品信息') : t('商品信息'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('分类'),
      field: 'categoryId',
      fieldLabel: 'categoryName',
      component: 'TreeSelect',
      componentProps: {
        api: categoryTreeData,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('商品名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('品牌名称'),
      field: 'brand',
      component: 'Input',
      componentProps: {
        maxlength: 128,
      },
      required: true,
    },
    {
      label: t('型号规格'),
      field: 'model',
      component: 'Input',
      componentProps: {
        maxlength: 128,
      },
      required: true,
    },
    {
      label: t('详细参数'),
      field: 'specifications',
      component: 'Input',
      required: true,
    },
    {
      label: t('市场价'),
      field: 'marketPrice',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { md: 24, lg: 24 },
    },
    {
      label: t('图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'jydqProduct_image',
        uploadType: 'image',
      },
      colProps: { md: 24, lg: 24 },
    },
  ];

  const options: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        lineStyle: {
          width: 1,
          color: '#019680',
        },
      },
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '10',
        '11',
        '12',
        '13',
        '14',
        '15',
        '16',
        '17',
        '18',
        '19',
        '20',
        '21',
        '22',
        '23',
        '24',
        '25',
        '26',
        '27',
        '28',
        '29',
        '30',
        '31',
      ],
      splitLine: {
        show: true,
        lineStyle: {
          width: 1,
          type: 'solid',
          color: 'rgba(226,226,226,0.5)',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: [
      {
        type: 'value',
        max: 8000,
        splitNumber: 4,
        axisTick: {
          show: false,
        },
        splitArea: {
          show: true,
          areaStyle: {
            color: ['rgba(255,255,255,0.2)'],
          },
        },
      },
    ],
    grid: { left: '1%', right: '1%', top: '2  %', bottom: 0, containLabel: true },
    series: [
      // {
      //   smooth: true,
      //   data: [
      //     111, 222, 4000, 18000, 33333, 55555, 66666, 33333, 14000, 36000, 66666, 44444, 22222,
      //     11111, 4000, 2000, 500, 333, 222, 111,
      //   ],
      //   type: 'line',
      //   areaStyle: {},
      //   itemStyle: {
      //     color: '#5ab1ef',
      //   },
      // },
      // {
      //   name: '123',
      //   smooth: true,
      //   data: [
      //     33, 66, 88, 333, 3333, 5000, 18000, 3000, 1200, 13000, 22000, 11000, 2221, 1201, 390,
      //     198, 60, 30, 22, 11,
      //   ],
      //   type: 'line',
      //   areaStyle: {},
      //   itemStyle: {
      //     color: '#019680',
      //   },
      // },
    ],
  };

  const serie = {
    name: '123',
    smooth: true,
    data: [

    ],
    type: 'line',
    areaStyle: {},
    itemStyle: {
      color: '#019680',
    },
  };

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await jydqProductForm(data);
    record.value = (res.jydqProduct || {}) as JydqProduct;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
    if (res.jydqProduct.prices) {
      console.log(res.jydqProduct.prices);
      let colorSpread = getColorSpread(res.jydqProduct.prices.size, 120);
      let i = 0;
      for (const key in res.jydqProduct.prices) {
        let value = res.jydqProduct.prices[key];
        // seriei 就是曲线图中的一条线
        const seriei = JSON.parse(JSON.stringify(serie));
        seriei.name = key;
        seriei.itemStyle.color = colorSpread[i];
        let j = 0;
        value.forEach((productPrice) => {
          seriei.data[j] = productPrice.currentPrice;
          j++;
        });
        options.series[i] = seriei;
        i++;
      };
    };
    options.yAxis[0].max = res.jydqProduct.marketPrice * 2;
    setOptions(options);
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await jydqProductSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  // 简化版均匀颜色生成器
  // 使用示例
  // console.log(getColorSpread(5, 120));
  // 输出：["#009688", "#00cc99", "#00ffaa", "#aaffee", "#ffeeff"]
  function getColorSpread(count, startHue = 0) {
    const colors = [];
    const hueStep = 360 / count;

    for(let i = 0; i < count; i++) {
      const hue = (startHue + i * hueStep) % 360;
      colors.push(hueToHex(hue, 0.8, 0.6)); // 固定饱和度80%和明度60%
    }
    return colors;
  }

  // HSL转HEX的精简版
  function hueToHex(h, s, l) {
    h /= 360;
    s /= 100;
    l /= 100;

    let r, g, b;
    if(s === 0) {
      r = g = b = l;
    } else {
      const c = (1 - Math.abs(2*l - 1)) * s;
      const x = c * (1 - Math.abs((h/60) % 2 - 1));
      const m = l - c/2;

      // 根据色相值计算RGB分量
      switch(Math.floor(h/60)) {
        case 0: r = c; g = x; b = 0; break;
        case 1: r = x; g = c; b = 0; break;
        case 2: r = 0; g = c; b = x; break;
        case 3: r = 0; g = x; b = c; break;
        case 4: r = x; g = 0; b = c; break;
        case 5: r = c; g = 0; b = x; break;
      }
    }
    return `#${(r*255).toString(16).padStart(2,'0')}${(g*255).toString(16).padStart(2,'0')}${(b*255).toString(16).padStart(2,'0')}`;
  }
</script>
